<template>
    <div id="map" style="height: 100%; width: 100%;display: flex;flex-direction: column;">
        <!--        <div class="content">-->
        <!--            <span>{{`经度：${lngLat.lng}`}}</span>-->
        <!--            <span>{{`纬度：${lngLat.lat}`}}</span>-->
        <!--        </div>-->
        <!--        <div class="__mouse__status" v-show="isShowTip">-->
        <!--            <div class="svg-wrapper">-->
        <!--                <svg t="1588512684752" class="icon" viewBox="0 0 1024 1024" version="1.1"-->
        <!--                     xmlns="http://www.w3.org/2000/svg" p-id="2024" width="16" height="16">-->
        <!--                    <path d="M435.2 768L908.8 294.4 864 249.6 412.8 700.8l-230.4-230.4-44.8 44.8 252.8 252.8z"-->
        <!--                          fill="#67C23A" p-id="2025"></path>-->
        <!--                </svg>-->
        <!--            </div>-->
        <!--            <span>已复制</span>-->
        <!--        </div>-->
    </div>

</template>

<script>
    import MapboxDirections from "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions"
    import mapboxgl from "mapbox-gl";
    import * as turf from "@turf/turf";
    import uavIcon from "../assets/img/uavIcon.jpeg"
    import {testLine} from "../components/map";
    import {GET_MAPBOX_MAP} from "../components/map/CreateMap";

    export default {
        name: "View",
        data() {
            return {
                // map: {},
                isShowTip: false,
                lngLat: {
                    lng: 115,
                    lat: 36
                },
                options: {
                    accuracy: 2
                },
                pointGeoJson: {
                    type: 'FeatureCollection',
                    features: [
                        {
                            type: 'Feature',
                            properties: {},
                            geometry: {
                                type: 'Point',
                                coordinates: [],
                            },
                        },
                    ],
                }
            }
        },

        mounted() {
            this.initMap();

            // 显示无人机轨迹

            // 显示无人机实时飞行

            // 无人机坐标更新
        },

        methods: {

            showUavLayerMap(values, bboxInfo) {
                //测试
                values = {
                    'type': 'FeatureCollection',
                    'features': [
                        {
                            'type': 'Feature',
                            'geometry': {
                                'type': 'LineString',
                                'coordinates': [[119.936876, 31.767053], [119.936876, 31.767053],[119.949493, 31.767053],[119.952111, 31.776137]]
                            }
                        }
                    ]
                };
                const animatePointGeoJson = this.pointGeoJson;
                const map = GET_MAPBOX_MAP();
                // 箭头-右
                let svgXML = `<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
<path d="M529.6128 512L239.9232 222.4128 384.7168 77.5168 819.2 512 384.7168 946.4832 239.9232 801.5872z" p-id="9085" fill="#ffffff"></path>
</svg>
`;

                //给图片对象写入base64编码的svg流
                var svgBase64 = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgXML)));

                let arrowIcon = new Image(20, 20);

                arrowIcon.src = svgBase64;

                arrowIcon.onload = function () {
                    map.addImage('arrowIcon', arrowIcon);
                    SET_ROUTE_DATA();
                };

                let steps = 0;
                let aLength = 0;
                let newRouteGeoJson;
                let routeGeoJson = values;

                // 获取轨迹边界
                var bbox = turf.bbox(routeGeoJson);
                //  测试
                bboxInfo = turf.bboxPolygon(bbox);
                console.log("boooooox----" + bbox); // 输出: [-180.0, -90.0, 180.0, 90.0]
                map.fitBounds(
                    [
                        [Number(bbox[0]), Number(bbox[1])],
                        [Number(bbox[2]), Number(bbox[3])],
                    ],
                    {
                        padding: {top: 100, bottom: 100, left: 100, right: 100},
                        maxZoom: 16,
                    },
                );

                // 获取轨迹数据
                function SET_ROUTE_DATA() {
                    animatePointGeoJson.features[0].geometry.coordinates = routeGeoJson.features[0].geometry.coordinates[0];
                    aLength = routeGeoJson.features[0].geometry.coordinates.length;
                    newRouteGeoJson = REST_ROUTE(routeGeoJson.features[0], 1000, 'kilometers');
                    steps = newRouteGeoJson.geometry.coordinates.length;

                    ADD_ROUTE_BBOX_LAYER(); // 添加轨迹边界图层
                    ADD_ROUTE_LAYER(); // 添加轨迹线图层
                    // addRealRouteSource(); // 添加实时轨迹线图层
                    ADD_ARROW_LAYER(); // 添加箭头图层
                    // addAnimatePointSource(); // 添加动态点图层
                }

                // 添加轨迹边界图层
                function ADD_ROUTE_BBOX_LAYER() {
                    map.addLayer({
                        id: 'routeBboxLayer',
                        type: 'line',
                        source: {
                            type: 'geojson',
                            data: bboxInfo,
                        },
                        paint: {
                            'line-color': '#fbc219',
                            'line-width': 3,
                            'line-dasharray': [5, 5],
                            'line-offset': -10,
                        },
                    });
                }

                // 添加轨迹线图层
                function ADD_ROUTE_LAYER() {
                    map.addLayer({
                        id: 'routeLayer',
                        type: 'line',
                        source: {
                            type: 'geojson',
                            lineMetrics: true,
                            data: routeGeoJson,
                        },
                        paint: {
                            'line-width': 10,
                            'line-opacity': 1,
                            'line-color': '#009EFF',
                        },
                    });
                }

                // 添加箭头图层
                function ADD_ARROW_LAYER() {
                    map.addLayer({
                        id: 'arrowLayer',
                        type: 'symbol',
                        source: {
                            type: 'geojson',
                            data: routeGeoJson, //轨迹geojson格式数据
                        },
                        layout: {
                            'symbol-placement': 'line',
                            'symbol-spacing': 50, // 图标间隔，默认为250
                            'icon-image': 'arrowIcon', //箭头图标
                            'icon-size': 0.5,
                        },
                    });
                }

                function REST_ROUTE(route, nstep, units) {
                    var newroute = {
                        type: 'Feature',
                        geometry: {
                            type: 'LineString',
                            coordinates: [],
                        },
                    };

                    var lineDistance = turf.length(route);
                    var nDistance = lineDistance / nstep;

                    for (let i = 0; i < aLength - 1; i++) {
                        var from = turf.point(route.geometry.coordinates[i]);
                        var to = turf.point(route.geometry.coordinates[i + 1]);
                        let lDistance = turf.distance(from, to, {
                            units: units,
                        });

                        if (i == 0) {
                            newroute.geometry.coordinates.push(route.geometry.coordinates[0]);
                        }

                        if (lDistance > nDistance) {
                            let rings = LINE_MORE(from, to, lDistance, nDistance, units);

                            newroute.geometry.coordinates = newroute.geometry.coordinates.concat(rings);
                        } else {
                            newroute.geometry.coordinates.push(route.geometry.coordinates[i + 1]);
                        }
                    }

                    return newroute;
                }

                function LINE_MORE(from, to, distance, splitLength, units) {
                    var step = parseInt(distance / splitLength);
                    var leftLength = distance - step * splitLength;
                    var rings = [];
                    var route = turf.lineString([from.geometry.coordinates, to.geometry.coordinates]);

                    for (let i = 1; i <= step; i++) {
                        let nlength = i * splitLength;
                        let pnt = turf.along(route, nlength, {
                            units: units,
                        });

                        rings.push(pnt.geometry.coordinates);
                    }

                    if (leftLength > 0) {
                        rings.push(to.geometry.coordinates);
                    }

                    return rings;
                }
            },

            // 点击copy经纬度
            copyLngLat() {
                console.log("copyLngLat>>>>>>")
                this._simpleCopy(this.lngLat)
                this.copyTip()
            },

            // 简单copy
            _simpleCopy(lngLat, cb) {
                console.log("_simpleCopy.....")
                const input = document.createElement('input')
                input.setAttribute('id', '__mouse__position_input')
                input.value = `${lngLat.lng}  ${lngLat.lat}`
                document.querySelector('body').appendChild(input)
                input.select()
                document.execCommand('copy')
                document.body.removeChild(input)
                // this.copyTip()
            },

            copyTip() {
                if (!this.isShowTip) {
                    this.isShowTip = true
                    this.timer = setTimeout(() => {
                        this.isShowTip = false
                    }, 1000)
                }
            },

            // 获取经纬度坐标
            getLngLat() {
                this.map.on('mousemove', (e) => {
                    const accu = this.options.accuracy
                    this.lngLat.lng = e.lngLat.lng.toFixed(accu) // 经度
                    this.lngLat.lat = e.lngLat.lat.toFixed(accu) // 纬度
                })
            },

            initMap() {

                // this.map =  new Mapbox.Map({
                //     accessToken: 'pk.eyJ1IjoiemhhbmdmZWkzMTcwIiwiYSI6ImNtNnlnMmZpZTBnenYydm9pOHQ0MzF6Y2oifQ.7aFdSnD7Ilm3P7PhyTMWtw',
                //     container: 'uavMap',
                //     center: [-74.006292, 40.712666],
                //     zoom: 12,
                //     style: 'mapbox://styles/mapbox/streets-v12',
                //     loglevel: 'none'
                // });
                //
                // const directions = new MapboxDirections({
                //     accessToken: this.map.accessToken
                // });
                //
                // this.map.addControl(directions, 'top-left');


                // 启用定位功能
                // var geolocate = new mapboxgl.GeolocateControl({
                //     positionOptions: {
                //         enableHighAccuracy: true
                //     },
                //     trackUserLocation: true
                // })
                // map.addControl(geolocate);
                // geolocate.trigger();  //自动触发定位功能

                // 处理定位数据
                // map.on('geolocate', function (e) {
                //     var coordinates = e.coords;
                //     var position = [coordinates.longitude, coordinates.latitude];
                //
                //     // 在地图上添加标记
                //     new mapboxgl.Marker()
                //         .setLngLat(position)
                //         .addTo(map);
                //
                //     // 移动地图到用户位置
                //     map.flyTo({
                //         center: position,
                //         zoom: 15
                //     });
                // });

                // map.on('load', function () {
                //     map.addLayer({
                //         'id': '3d-buildings',
                //         'source': 'composite',
                //         'source-layer': 'building',
                //         'filter': ['==', 'extrude', 'true'],
                //         'type': 'fill-extrusion',
                //         'minzoom': 15,
                //         'paint': {
                //             'fill-extrusion-color': '#aaa',
                //
                //             // 使用光源
                //             'fill-extrusion-height': [
                //                 'interpolate',
                //                 ['linear'],
                //                 ['zoom'],
                //                 15,
                //                 0,
                //                 15.05,
                //                 ['get', 'height']
                //             ],
                //             'fill-extrusion-base': [
                //                 'interpolate',
                //                 ['linear'],
                //                 ['zoom'],
                //                 15,
                //                 0,
                //                 15.05,
                //                 ['get', 'min_height']
                //             ],
                //             'fill-extrusion-opacity': 0.6
                //         }
                //     });
                // })
                testLine();
                // this.showUavLayerMap();
            },


        },
        // watch: {
        //     map: {
        //         handler: function (newVal, oldVal) {
        //             console.log("watch...")
        //             this.map = newVal
        //             this.getLngLat()
        //         }
        //     }
        // },
    }
</script>

<style scoped>
    /*.mapboxgl-ctrl-bottom-left .mapboxgl-ctrl-bottom-right {*/
    /*    display: none;*/
    /*}*/

    /*.content {*/
    /*    span {*/
    /*        display: inline-block;*/
    /*        width: 90px;*/
    /*        height: 24px;*/
    /*        line-height: 24px;*/
    /*        font-family: PingFangSC-Regular;*/
    /*        font-size: 12px;*/
    /*        color: #44474A;*/
    /*        letter-spacing: 0;*/
    /*        &:first-child {*/
    /*            margin-right: 10px;*/
    /*        }*/
    /*    }*/
    /*}*/

    /*.__mouse__status {*/
    /*    position: absolute;*/
    /*    top: -40px;*/
    /*    right: 0;*/
    /*    padding: 0 6px;*/
    /*    height: 30px;*/
    /*    line-height: 30px;*/
    /*    border-radius: 4px;*/
    /*    background-color: #FFFFFF;*/
    /*    animation: fade ease-in 0.2s;*/

    /*.svg-wrapper {*/
    /*    display: inline-block;*/
    /*    vertical-align: sub;*/
    /*}*/

    /*.__mouse__status span {*/
    /*    display: inline-block;*/
    /*    margin-left: 2px;*/
    /*}*/

    /*}*/

    /*@keyframes fade {*/
    /*    from {*/
    /*        top: 0;*/
    /*        opacity: 0;*/
    /*    }*/
    /*    to {*/
    /*        top: -40px;*/
    /*        opacity: 1;*/
    /*    }*/
    /*}*/
</style>
